package com.cm.figure.service.pictureService;

import com.cm.figure.dao.PicturesMapper;
import com.cm.figure.model.Pageing;
import com.cm.figure.model.Pictures;
import com.cm.figure.model.Server;
import com.cm.figure.utility.FileUtility;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * ClassName:PictureServiceImp
 * Package:com.cm.figure.service.userService
 * Description:
 *
 * @Date:2021/8/16 22:03
 * @com.chuangmei
 */

@Service
public class PictureServiceImp implements PictureService {


    @Resource
    private PicturesMapper picturesDao;

    /**
     * 通过userid查询图片
     * @param userid
     * @return 图片数组
     */
    @Override
    public Pictures[] queryPicturesByUserId(Long userid) {

        Pictures[] pictures = picturesDao.selectPicturesByUserId(userid);

        return pictures;
    }

    /**
     * 通过id删除图片
     * @return id
     */
    @Override
    public int removePictureById(Long id) {

        // 返回状态
        int database = 0;
        int file = 0;

        //查询图片所属的user
        Pictures pictures = picturesDao.selectPicturesAndUserByPictureId(id);

        String path = null;

        // 如果不为空
        if (Server.isLocal){
            path = pictures.getFilepath() + "\\" + pictures.getFilename();
        }else {
            path = pictures.getFilepath() + "/" + pictures.getFilename();
        }

        // 删除数据库中的图片
        if (null != pictures) {
            int count = picturesDao.deleteByPrimaryKey(id);
            database = count;   //判断数据库是否删除成功
        }

        //调用工具类删除服务器的图片
        boolean ok = FileUtility.deleteFile(path);

        // 判断服务器是否删除成功
        if (ok){
            file = 1;
        }

        return database + file;
    }

    /**
     * 分页查询图片
     * @param userid
     * @param pageing
     * @return
     */
    @Override
    public Pictures[] queryPicturesPageing(Long userid, Pageing pageing) {

        return picturesDao.selectPicturesPageing(userid,(pageing.getCurrentPage() - 1) * pageing.getPageSize(), pageing.getPageSize());
    }

    @Override
    public Integer queryPicturesTotalByUserId(Long userid) {

        return picturesDao.selectPicturesTotalByUserId(userid);
    }
}
